import {
    EventBus
} from '@syt/nativemessenger'

import CreateUuid from '../uuid'
import promiseTimeout from '../promiseTimeout'

const fetch = function (req) {
    const uuid = CreateUuid()
    const eventName = `$plugin:NetClient:complete:${uuid}`
    const errEventName = `$plugin:NetClient:err:${uuid}`
    req.baseUrl = window.baseUrl
    req.uuid = uuid
    return new Promise(function (resolve, reject) { 
        EventBus.share.on(eventName, function (res) { 
            resolve(res);
            if (res.isRemoveEvent) {
                EventBus.share.bus.$off(eventName)
                EventBus.share.bus.$off(errEventName)
            }
        })

        EventBus.share.on(errEventName, function (err) {
            reject(error);
            EventBus.share.bus.$off(eventName)
            EventBus.share.bus.$off(errEventName) 
        })

        EventBus.share.native('$plugin:NetClient', req)

    })
}

// const timout = promiseTimeout(5000, fetch())

export default fetch